package com.gqk.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gqk.helper.MenuHelper;
import com.gqk.mapper.SysMenuMapper;
import com.gqk.mapper.SysRoleMenuMapper;
import com.gqk.model.system.SysMenu;
import com.gqk.model.system.SysRoleMenu;
import com.gqk.vo.system.AssginMenuVo;
import com.gqk.vo.system.MetaVo;
import com.gqk.vo.system.RouterVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;


@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements
        SysMenuService{

    //依赖注入SysMenuMapper
    @Autowired
    private SysMenuMapper sysMenuMapper;
    @Autowired
    private SysRoleMenuMapper sysRoleMenuMapper;
    @Override
    public List<SysMenu> findNodes() {
        //查询全部的权限列表
        List<SysMenu> sysMenuList = this.list();
        if((CollectionUtils.isEmpty(sysMenuList))) return null;
        //构建树形数据
        List<SysMenu> result = MenuHelper.buildTree(sysMenuList);
        return result;
    }
    //根据角色获取授权权限数据
    @Override
    public List<SysMenu> findSysMenuByRoleId(Long roleId) {
        //全部权限列表(所有的菜单)
        List<SysMenu> allSysMenuList = this.list(new
                LambdaQueryWrapper<SysMenu>().eq(SysMenu::getStatus, 1));
        System.out.println(allSysMenuList);

        //根据角色id获取角色权限(角色下面的所有的列表)
        List<SysRoleMenu> sysRoleMenuList =
                sysRoleMenuMapper.selectList(new
                        LambdaQueryWrapper<SysRoleMenu>
                        ().eq(SysRoleMenu::getRoleId, roleId));
        System.out.println(sysRoleMenuList);
        System.out.println("==============================");
        //将菜单的id抽取 出来存放在了List集合中
        List<Long> menuIdList = sysRoleMenuList.stream().map(e
                -> e.getMenuId()).collect(Collectors.toList());
        allSysMenuList.forEach(permission -> {
            if (menuIdList.contains(permission.getId())) {//判断是否存在此菜单
                permission.setSelect(true);//存在钩中
            } else {
                permission.setSelect(false);
            }
        });
        List<SysMenu> sysMenuList =
                MenuHelper.buildTree(allSysMenuList);
        return sysMenuList;
    }
    //保存角色权限
    @Override
    public void doAssign(AssginMenuVo assginMenuVo) {
        // 删除已有的菜单
        sysRoleMenuMapper.delete(new LambdaQueryWrapper<SysRoleMenu>()
                .eq(SysRoleMenu::getRoleId,assginMenuVo.getRoleId()));
        // 遍历assignMenuVO的要添加的菜单列表
        for(Long menuId: assginMenuVo.getMenuIdList()){
            if(StringUtils.isEmpty(menuId)) continue;
            SysRoleMenu sysRoleMenu = new SysRoleMenu();
            sysRoleMenu.setRoleId(assginMenuVo.getRoleId());
            sysRoleMenu.setMenuId(menuId);
            sysRoleMenuMapper.insert(sysRoleMenu);
        }
    }

    @Override
    public List<RouterVo> findUserMenuList(Long userId) {
        //超级管理员admin账号id为：1
        List<SysMenu> sysMenuList = null;
        if (userId.longValue() == 1) {
            sysMenuList = this.list(new LambdaQueryWrapper<SysMenu>
                    ().eq(SysMenu::getStatus, 1).orderByAsc(SysMenu::getSortValue));
        } else {
            sysMenuList = sysMenuMapper.findListByUserId(userId);
        }
//构建树形数据
        List<SysMenu> sysMenuTreeList = MenuHelper.buildTree(sysMenuList);
        List<RouterVo> routerVoList = this.buildMenus(sysMenuTreeList);
        return routerVoList;
    }

    @Override
    public List<String> findUserPermsList(Long userId) {
        //超级管理员admin账号id为：1
        List<SysMenu> sysMenuList = null;
        if (userId.longValue() == 1) {
            sysMenuList = this.list(new LambdaQueryWrapper<SysMenu>
                    ().eq(SysMenu::getStatus, 1));
        } else {
            sysMenuList = sysMenuMapper.findListByUserId(userId);
        }
        List<String> permsList = sysMenuList.stream().filter(item -> item.getType()
                == 2).map(item -> item.getPerms()).collect(Collectors.toList());
        return permsList;
    }

    private List<RouterVo> buildMenus(List<SysMenu> menus) {
        List<RouterVo> routers = new LinkedList<RouterVo>();
        for (SysMenu menu : menus) {
            RouterVo router = new RouterVo();
            router.setHidden(false);
            router.setAlwaysShow(false);
            router.setPath(getRouterPath(menu));
            router.setComponent(menu.getComponent());
            router.setMeta(new MetaVo(menu.getName(), menu.getIcon()));
            List<SysMenu> children = menu.getChildren();
//如果当前是菜单，需将按钮对应的路由加载出来，如：“角色授权”按钮对应的路由在“系统管理”下面
            if(menu.getType().intValue() == 1) {
                List<SysMenu> hiddenMenuList = children.stream().filter(item ->
                        !StringUtils.isEmpty(item.getComponent())).collect(Collectors.toList());
                for (SysMenu hiddenMenu : hiddenMenuList) {
                    RouterVo hiddenRouter = new RouterVo();
                    hiddenRouter.setHidden(true);
                    hiddenRouter.setAlwaysShow(false);
                    hiddenRouter.setPath(getRouterPath(hiddenMenu));
                    hiddenRouter.setComponent(hiddenMenu.getComponent());
                    hiddenRouter.setMeta(new MetaVo(hiddenMenu.getName(),
                            hiddenMenu.getIcon()));
                    routers.add(hiddenRouter);
                }
            } else {
                if (!CollectionUtils.isEmpty(children)) {
                    if(children.size() > 0) {
                        router.setAlwaysShow(true);
                    }
                    router.setChildren(buildMenus(children));
                }
            }
            routers.add(router);
        }
        return routers;
    }

    /**
     * 获取路由地址
     *
     * @param menu 菜单信息
     * @return 路由地址
     */
    public String getRouterPath(SysMenu menu) {
        String routerPath = "/" + menu.getPath();
        if(menu.getParentId().intValue() != 0) {
            routerPath = menu.getPath();
        }
        return routerPath;
    }

}
